var path = require('path');
var fs = require('fs');

var express = require('express');
var proxy = require('http-proxy-middleware');
var is_there = require("is-there");
var mime = require("mime");

var base_path = path.dirname(__dirname);

// 发送文件
function sendFile(res, req_path) {
    var file_path = req_path;
    // 避免当 file_path 为 undefined 时报错
    if(!file_path) {
        file_path = '';
    }
    if(file_path == '') {
        file_path = 'index.html';
    }
    var full_path = path.join(
        base_path,
        'public', 'pages',
        file_path
    );
    if(is_there.file(full_path)) {
        var stat = fs.lstatSync(full_path);
        var size = stat.size;
        var mime_type = mime.getType(full_path)
        res.status(200);
        res.set('Content-Length', (size).toString());
        res.set('Content-Type', mime_type);
        var stream = fs.createReadStream(full_path);
        stream.pipe(res);

        stream.on('data', function(data) {
            res.write(data);
        });

        stream.on('end', function() {
            res.end();
        });
        return true;
    }
    else {
        res.status(404).set('Content-Length', '0');
        return false;
    }
}

var router = express.Router();

// 绑定路由
router.all(/.*/, function(req, res, next) {
    var send_ok = sendFile(res, req.path);
    if(!send_ok) {
        next();
    }
});


module.exports = router;